//
//  ParentListViewController.m
//  iBaby365v2
//
//  Created by Kirinrin on 14-7-5.
//  Copyright (c) 2014年 suplus. All rights reserved.
//

#import "ParentListViewController.h"
#import "NetworkAccessManager.h"
#import <UIActivityIndicatorView+AFNetworking.h>
#import "UIAlertView+Kirinrin.h"
#import "ParentInfo.h"
#import "ContactListCell.h"
#import "ChatViewController.h"

@interface ParentListViewController ()
//@property(strong, nonatomic)NSDictionary *tableSortData;

@property (strong, nonatomic) IBOutlet UIActivityIndicatorView *activityIndicator;
@property(strong, nonatomic)NSArray *tableData;
@property (strong, nonatomic)NSArray *sectionIndexArray;
@property (strong, nonatomic) IBOutlet UITableView *tableView;

@end

@implementation ParentListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
//        self.title = @"家长列表";
    }
    return self;
}
-(id)init{
    self = [super init];
    if (self) {
//        self.title = @"家长列表";
    }
    return self;
}

- (void)viewDidLoad
{
    NSLog(@"viewDidLoad");
    
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
//    [self.tableView removeFromSuperview];
    self.activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
//    self.activityIndicator.color = [UIColor blackColor];
    self.activityIndicator.center = CGPointMake(self.view.center.x, 15);
    [self.activityIndicator startAnimating];
//    self.activityIndicator.hidesWhenStopped = NO;
    [self.view addSubview:self.activityIndicator];
    
    [self loadRemoteData];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)loadRemoteData{
    NSLog(@"loadRemoteData");
    NSString *uriString = [NSString stringWithFormat:@"Parent/%@/queryWithClass.json", self.appDelegate.user[@"kClassId"]];
    NSDictionary *parameters = @{@"key": self.appDelegate.accessKey};
    
    AFHTTPRequestOperation *opernation = [[NetworkAccessManager shareManager]GET:uriString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"opernation: %@\nresponse: %@", operation, responseObject);
        
        int resultCode = [responseObject[@"result"]intValue];
        if (resultCode == 0) {
            
            NSArray *dataList = [ParentInfo parentsWithDictionaryArray :responseObject[@"data"]];
            
            NSDictionary *result = [ParentInfo sortAndIndexWithPinyinLetter:dataList];
            self.tableData = result[@"data"];
            self.sectionIndexArray = result[@"index"];
//            CGRect content = self.view.frame;

//            [self.view addSubview: self.tableView];
//            self.tableView.frame = content;
//            content = self.tableView.frame;
            [self.tableView reloadData];
//            [self.view setNeedsDisplay];
        }else{
            [UIAlertView alertWithRemoteError:resultCode];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"opernation: %@\nerror: %@", operation, error);
        [UIAlertView alertWithNetworkError];
    }];
    [self.activityIndicator setAnimatingWithStateOfOperation:opernation];
}


#pragma mark - Navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
 
 if ([segue.identifier isEqualToString: @"toChater"]) {
     ChatViewController *destViewController = segue.destinationViewController;
     ParentInfo *cellData = sender;
     destViewController.chatter = cellData.id;
     destViewController.chatterPhotoUrlString = cellData.photo;
     destViewController.navigationItem.title = cellData.name;
 }
 
}


#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"heightForRowAtIndexPath");
    return 60;
}
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section{
    UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
    [header.contentView setBackgroundColor: UIColorFromRGB(0xe9e9e9, 1)];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ParentInfo *cellData = self.tableData[indexPath.section][indexPath.row];

    [self performSegueWithIdentifier:@"toChater" sender:cellData];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    NSLog(@"numberOfSectionsInTableView");
    return [self.tableData count] ;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSLog(@"numberOfRowsInSection");
    return [[self.tableData objectAtIndex:section] count];
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    return self.sectionIndexArray;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return [self.sectionIndexArray objectAtIndex:section];
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    return index;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"numberOfRowsInSection");
    static NSString *cellIndetify = @"ContactListCell";
    ContactListCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndetify];
    cell.viewController = self;
    ParentInfo *cellData = self.tableData[indexPath.section][indexPath.row];
    
    cell.data = cellData;
    
    return cell;
}

#pragma mark - Action
- (IBAction)callParentCellPhoneAction:(id)sender {
    ContactListCell *cellView =(ContactListCell *)[[[sender superview]superview]superview];
    ParentInfo *data = cellView.data;
    UIAlertView *confirmView = [[UIAlertView alloc]initWithTitle:data.phoneNumber message:[NSString stringWithFormat:@"是否要拨打%@的电话",data.name] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    
    [confirmView show];
    
//    NSURL *phoneNumberURL = [NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",data.phoneNumber]];
//    [[UIApplication sharedApplication] openURL:phoneNumberURL];
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSLog(@"clickedButtonAtIndex %x", buttonIndex);
    switch (buttonIndex) {
        case 1:{
            NSURL *phoneNumberURL = [NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",alertView.title]];
            [[UIApplication sharedApplication] openURL:phoneNumberURL];
        }
            break;
            
            
        default:
            break;
    }
}
@end
